package com.wirelesshomecontrol.gui;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.rapplogic.xbee.api.*;
import com.rapplogic.xbee.examples.RemoteAtExample;
import com.vaadin.Application;
import com.vaadin.data.util.QueryContainer;
import com.vaadin.terminal.Sizeable;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.wirelesshomecontrol.TranscieverControl;
import com.wirelesshomecontrol.db.jdbcconnect;
import com.wirelesshomecontrol.gui.windows.AboutWindow;
import com.wirelesshomecontrol.gui.windows.AddingModuleWindow;
import com.wirelesshomecontrol.gui.windows.DeleteModuleWindow;
import com.wirelesshomecontrol.gui.windows.HistoryWindow;
import com.wirelesshomecontrol.gui.windows.ModuleViewWindow;
import com.wirelesshomecontrol.gui.windows.SearchingWindow;
import com.wirelesshomecontrol.gui.windows.SettingsWindow;

public class WirelessHomeControlWindow extends Window {

	// Toolbar Buttons
	private Button btn_add_module = new Button("Add Module");
	private Button btn_del_module = new Button("Delete Module");
	private Button btn_settings = new Button("Settings");
	private Button btn_history = new Button("History");
	private Button btn_about = new Button("About");
	private Button btn_status1 = new Button("Power");
	private Button btn_status2 = new Button("Power");
	private Button btn_test_on = new Button("Enable");
	private Button btn_test_off = new Button("Disable");

	private jdbcconnect cn = new jdbcconnect();

	XBeeAddress64 address1 = new XBeeAddress64(0, 0, 0, 0, 0, 0, 0, 0);
	XBeeAddress64 address2 = new XBeeAddress64(0, 0, 0, 0, 0, 0, 0, 1);
	public String nickname1 = "Box Red";
	public String nickname2 = "Box Blue";

	public String poweron = "ON";
	public String poweroff = "OFF";

	public int statusOn = 1;
	public int statusOff = 0;
	public int idsensor1=1;
	public int idsensor2=2;
	public Table tblDataTable = null;
	public String COMport= "COM6";
	public XBee Xbee = new XBee();
	public TranscieverControl ctr = new TranscieverControl();
	public HorizontalLayout toolbarL = new HorizontalLayout();

	// private final static Logger log =
	// Logger.getLogger(WirelessHomeControlWindow.class);

	public WirelessHomeControlWindow() throws Exception {
		super("Wireless Home Control Window");
		setName("Main Window");
		setTheme("chameleon-dark");
		// PropertyConfigurator.configure("log4j.properties");
		initUI();
	}

	private void initUI() throws Exception {
		addComponent(createToolbar());

		/*
		 * Start by checking if element 1 exists on table, if it does create
		 * button corresponding to that box redo for box 2 If statement to check
		 * status method to check status, set status for that box
		 */
		
		/*if(ctr.getD5Status(Xbee)){
			//cn.Update_Status_DB(idsensor1, statusOn);
		
		}else {
			//cn.Update_Status_DB(idsensor1, statusOff);
		}*/
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(cn.dbUrl, "root",
					"Hippos44");
			/*
			 * cn.qcSQLSensor = new
			 * QueryContainer("SELECT nickname, sensor_address FROM sensors",
			 * con); tblDataTable = new Table(); tblDataTable.setWidth(90,
			 * Sizeable.UNITS_PERCENTAGE);
			 * tblDataTable.setContainerDataSource(cn.qcSQLSensor);
			 * 
			 * tblDataTable.setVisible(true); tblDataTable.setEnabled(true);
			 * tblDataTable.setCaption("SENSORS"); tblDataTable.setSizeFull();
			 * addComponent(tblDataTable);
			 */
			String query = "Select status from sensors where sensor_address = '0, 0, 0, 0, 0, 0, 0, 0' and status = 1";
			PreparedStatement stmt = con.prepareStatement(query);
			stmt.execute();
			ResultSet rs = stmt.getResultSet();
			int count = 0;
			while (rs.next()) {
				++count;
			}

			if (count > 0) {
				btn_status1.setCaption(nickname1 + " Power On");
				btn_status1.setIcon(new ThemeResource("images/light_on.png"));
			} else {
				btn_status1.setCaption(nickname1 + " Power Off");
				btn_status1.setIcon(new ThemeResource("images/light_off.png"));
			}
			addComponent(toolbarL);
			toolbarL.addComponent(btn_status1);
			// cn.qcSQLHistory.close(); // Closes Query Can Not reopen

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		/*
		 * btn_test_on.setIcon(new ThemeResource("images/light_on.png"));
		 * btn_test_off.setIcon(new ThemeResource("images/light_off.png"));
		 * toolbarL.addComponent(btn_test_on);
		 * 
		 * toolbarL.addComponent(btn_test_off);
		 */

		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(cn.dbUrl, "root",
					"Hippos44");
			String query = "Select status from sensors where sensor_address = '0, 0, 0, 0, 0, 0, 0, 1' and status = 1";
			PreparedStatement stmt = con.prepareStatement(query);
			stmt.execute();
			ResultSet rs = stmt.getResultSet();
			int count = 0;
			while (rs.next()) {
				++count;
			}

			if (count > 0) {
				btn_status2.setCaption(nickname2 + " Power On");
				btn_status2.setIcon(new ThemeResource("images/light_on.png"));
			} else {
				btn_status2.setCaption(nickname2 + " Power Off");
				btn_status2.setIcon(new ThemeResource("images/light_off.png"));
			}
			toolbarL.addComponent(new Label("<br /> <br /> <br />",
					Label.CONTENT_XHTML));
			addComponent(toolbarL);
			toolbarL.addComponent(btn_status2);
			// cn.qcSQLHistory.close(); // Closes Query Can Not reopen

		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		toolbarL.addComponent(btn_test_on);
		toolbarL.addComponent(btn_test_off);
	}

	private HorizontalLayout createToolbar() {
		HorizontalLayout toolbar = new HorizontalLayout();

		// toolbar.addComponent(btn_add_module);
		// toolbar.addComponent(btn_del_module);
		toolbar.addComponent(btn_history);
		toolbar.addComponent(btn_settings);
		toolbar.addComponent(btn_about);
		toolbarL.addComponent(btn_test_on);
		toolbarL.addComponent(btn_test_off);

		btn_add_module.setIcon(new ThemeResource("icons/32/Add_Button-32.png"));
		btn_del_module.setIcon(new ThemeResource("icons/32/Close-32.png"));
		btn_history.setIcon(new ThemeResource("icons/32/Chart-32.png"));
		btn_settings.setIcon(new ThemeResource("icons/32/Configure-32.png"));
		btn_about.setIcon(new ThemeResource("icons/32/Info-32.png"));

		btn_test_on.setIcon(new ThemeResource("images/light_on.png"));
		btn_test_off.setIcon(new ThemeResource("images/light_off.png"));

		btn_add_module.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				Window search = new SearchingWindow().getSearchingWindow();
				addWindow(search);
				addWindow(new AddingModuleWindow().getAddingWindow());
				try {
					ctr.getInputAnalog(Xbee, "COM6", null);
				} catch (XBeeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		btn_del_module.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				addWindow(new DeleteModuleWindow().getDelete());
			}
		});

		btn_about.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				addWindow(new AboutWindow().getAbout());
			}
		});

		btn_history.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				addWindow(new HistoryWindow().getHistory());

			}
		});

		btn_settings.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				addWindow(new SettingsWindow().getSettings()); // works

			}
		});
		
		btn_test_on.addListener(new Button.ClickListener() {
			XBee xbee = new XBee();
			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				try {
					// replace with your coordinator com/baud
					xbee.open("COM6", 9600);
					// xbee.open("COM5", 9600);			
					
					// replace with SH + SL of your end device
					XBeeAddress64 addr64 = new XBeeAddress64(0, 0, 0, 0, 0, 0, 0, 0);
					
					RemoteAtRequest requestD3 = new RemoteAtRequest(addr64, "D3", new int[] {5});
					RemoteAtRequest requestD1 = new RemoteAtRequest(addr64, "D1", new int[] {5});
					
					RemoteAtResponse response1 = (RemoteAtResponse) xbee.sendSynchronous(requestD1, 10000);
					RemoteAtResponse response2 = (RemoteAtResponse) xbee.sendSynchronous(requestD3, 10000);
				
					if (response1.isOk() && response2.isOk()) {
						//log.info("successfully turned on pin 20 (D0)");	
					} else {
						throw new RuntimeException("failed to turn on pin 20.  status is " + response1.getStatus());
					} 
					
				} catch (XBeeTimeoutException e) {
					//log.error("request timed out. make sure you remote XBee is configured and powered on");
				} catch (Exception e) {
					//log.error("unexpected error", e);
				} finally {
					xbee.close();
				}
				showNotification("Module Power Enabled");
			}
		});
		
		btn_test_off.addListener(new Button.ClickListener() {
			XBee xbee = new XBee();
			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				try {
					// replace with your coordinator com/baud
					xbee.open("COM6", 9600);
					// xbee.open("COM5", 9600);			
					
					// replace with SH + SL of your end device
					XBeeAddress64 addr64 = new XBeeAddress64(0, 0, 0, 0, 0, 0, 0, 0);
					
					RemoteAtRequest requestD3 = new RemoteAtRequest(addr64, "D3", new int[] {4});
					RemoteAtRequest requestD1 = new RemoteAtRequest(addr64, "D1", new int[] {4});
					
					RemoteAtResponse response1 = (RemoteAtResponse) xbee.sendSynchronous(requestD1, 10000);
					RemoteAtResponse response2 = (RemoteAtResponse) xbee.sendSynchronous(requestD3, 10000);
				
					if (response1.isOk() && response2.isOk()) {
						//log.info("successfully turned on pin 20 (D0)");	
					} else {
						throw new RuntimeException("failed to turn on pin 20.  status is " + response1.getStatus());
					} 
					
				} catch (XBeeTimeoutException e) {
					//log.error("request timed out. make sure you remote XBee is configured and powered on");
				} catch (Exception e) {
					//log.error("unexpected error", e);
				} finally {
					xbee.close();
				}
				showNotification("Module Power Disabled");
			}
		});
		btn_status1.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				String text = btn_status1.getCaption();
				if (text.equals(nickname1 + " Power Off")) {
					btn_status1.setCaption(nickname1 + " Power On");
					try {
						//ctr.changeStatus(Xbee, "COM6");
						ctr.XBeeOn(address1);
					} catch (XBeeException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InterruptedException e) {  //needed for Xbeeon
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					btn_status1.setIcon(new ThemeResource("images/light_on.png"));
					// Update Sensors History
					cn.Update_Sensor_Data_DB(
							"0, 0, 0, 0, 0, 0, 0, 0",
							nickname1,
							poweron,
							new java.sql.Timestamp(new java.util.Date()
									.getTime()));
					// Update Sensor status
					cn.Update_Status_DB(idsensor1, statusOn);
				} else if (text.equals(nickname1 + " Power On")) {
					btn_status1.setCaption(nickname1 + " Power Off");
					try {
						ctr.XBeeOff(address1);
						//ctr.changeStatus(Xbee, "COM6");
					} catch (XBeeException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					btn_status1.setIcon(new ThemeResource(
							"images/light_off.png"));
					// Update Sensors History
					cn.Update_Sensor_Data_DB("0, 0, 0, 0, 0, 0, 0, 0", nickname1, poweroff,
							new java.sql.Timestamp(new java.util.Date().getTime()));
					// Update Sensor status
					cn.Update_Status_DB(idsensor1, statusOff);

				}
							}
		});

		btn_status2.addListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				showNotification("Module Disabled");
				
			}
		});

		toolbar.setMargin(true);
		toolbar.setSpacing(true);

		toolbar.setStyleName("toolbar");

		toolbar.setWidth("100%");

		Embedded em = new Embedded("", new ThemeResource("images/logo-32.png"));
		toolbar.addComponent(em);
		toolbar.setComponentAlignment(em, Alignment.TOP_RIGHT);
		toolbar.setExpandRatio(em, 1);

		return toolbar;
	}
}